package com.ukefu.webim.web.handler.admin.mycallcenter;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.freeswitch.model.CallCenterAgent;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.impl.CallOutQuene;
import com.ukefu.webim.service.repository.*;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/mycallcenter")
public class MyCallCenterExtentionController extends Handler{
	
	@Autowired
	private PbxHostRepository pbxHostRes ;
	
	@Autowired
	private UserRepository userRes ;
	
	@Autowired
	private ExtentionRepository extentionRes;
	
	@Autowired
	private SipTrunkRepository sipTrunkRes ;
	
	@Autowired
	private MediaRepository mediaRes ;
	
	@Autowired
	private ServiceAiRepository serviceAiRes ;
	
	@Autowired
	private SalesPatterRepository salesPatterRes ;
	
	@Autowired
	private QueSurveyProcessRepository queSurveyProcessRes ;
	
	@Autowired
	private NumberPoolRepository numberPoolRepository;

	@Autowired
	private NumberPoolExtentionRelaRepository numberPoolExtentionRelaRepository;

	@Autowired
	private TenantRepository tenantRepository;

	@RequestMapping(value = "/extention")
	@Menu(type = "callcenter" , subtype = "callcenterresource" , access = false )
	public ModelAndView extention(ModelMap map , HttpServletRequest request , @Valid final String hostid, @Valid final Extention extention) {
		PbxHost pbxHost = pbxHostRes.findById(hostid) ;
		//map.addAttribute("pbxHostList" , pbxHostList);
		final String orgi = super.getOrgi(request);
		if(pbxHost != null){
			map.addAttribute("pbxHost" , pbxHost);

			Page<Extention> extentionPageList = extentionRes.findAll(new Specification<Extention>() {
				@Override
				public Predicate toPredicate(Root<Extention> root,
											 CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();
					list.add(cb.equal(root.get("hostid").as(String.class), hostid));
					list.add(cb.equal(root.get("orgi").as(String.class),orgi));
					Predicate[] p = new Predicate[list.size()];
					return cb.and(list.toArray(p));
				}
			}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.ASC, "extention","createtime"));
			map.addAttribute("extentionList" , extentionPageList.getContent());
			map.addAttribute("extentionPageList" , extentionPageList);
		}
		return request(super.createRequestPageTempletResponse("/admin/mycallcenter/extention/index"));
	}

	@RequestMapping(value = "/extention/add")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentionadd(ModelMap map , HttpServletRequest request , @Valid String hostid) {
		if(super.isEnabletneant()){
			map.addAttribute("pbxHost" , pbxHostRes.findById(hostid));
		}else{
			map.addAttribute("pbxHost" , pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request)));
		}
		//map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));

		//map.addAttribute("numberPoolList",numberPoolRepository.findByHostid(hostid));

//		if(super.isEnabletneantAndSuperUser(request)) {
//			//多租户下 可以绑定租户
//			map.addAttribute("tenantList", tenantRepository.findByDatastatus(false));
//		}
//		if(super.isEnabletneantAndSuperUser(request)){
//			//启用多租户和超级管理员 显示全部
//			map.addAttribute("mediaList" , mediaRes.findByHostid(hostid));
//		}else{
//			map.addAttribute("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
//		}
    	return request(super.createRequestPageTempletResponse("/admin/mycallcenter/extention/add"));
    }
	
	@RequestMapping(value = "/extention/save")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentionsave(ModelMap map , HttpServletRequest request , @Valid Extention extention,@Valid String[] numberPool) {
		if(!StringUtils.isBlank(extention.getExtention()) && !StringUtils.isBlank(extention.getPassword())){
			String[] extstr = extention.getExtention().split("[,， ]") ;
			int extnum = 0 ;
			String orgi = super.getOrgi(request);

			for(String ext : extstr){
				if(ext.matches("[\\d]{3,8}")){	//分机号码最少3位数字
					createNewExtention(ext, super.getUser(request), extention.getHostid(), extention.getPassword(), orgi , extention,numberPool) ;
				}else{
					String[] ph = ext.split("[~-]") ;
					if(ph.length == 2 && ph[0].matches("[\\d]{3,8}") && ph[1].matches("[\\d]{3,8}") && ph[0].length() == ph[1].length()){
						int start = Integer.parseInt(ph[0]) ;
						int end = Integer.parseInt(ph[1]) ;
						
						for(int i= start ; i <= end && extnum < 100 ; i++){	//最大一次批量生产的 分机号不超过100个
							createNewExtention(String.valueOf(i), super.getUser(request), extention.getHostid(), extention.getPassword(), orgi , extention,numberPool) ;
						}
					}
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/mycallcenter/extention.html?hostid="+extention.getHostid()));
    }
	
	private Extention createNewExtention(String num , User user , String hostid , String password , String orgi , Extention src,String[] numberPool){
		Extention extno = new Extention();
		extno.setExtention(num);
		extno.setOrgi(orgi);
		extno.setCreater(user.getId());
		extno.setHostid(hostid);
		extno.setPassword(password);
		
		extno.setPlaynum(src.isPlaynum());
		extno.setCallout(src.isCallout());
		extno.setRecord(src.isRecord());
		extno.setExtype(src.getExtype());
		extno.setMediapath(src.getMediapath());
		
		extno.setSiptrunk(src.getSiptrunk());
		extno.setEnablewebrtc(src.isEnablewebrtc());
		extno.setAutoanswer(src.getAutoanswer());
		//int count = extentionRes.countByExtentionAndHostidAndOrgi(extno.getExtention() , hostid, orgi) ;
		//NOTE 同一个语音服务器下的分机唯一性 不管orgi是否一样
		int count = extentionRes.countByExtentionAndHostid(extno.getExtention() , hostid) ;
		if(count == 0){	
			extentionRes.save(extno) ;

			if(numberPool != null && numberPool.length > 0){
				for(String np : numberPool){
					if(StringUtils.isNotBlank(np)){
						NumberPoolExtentionRela npe = new NumberPoolExtentionRela();
						npe.setCreater(user.getId());
						npe.setOrgi(orgi);
						npe.setCreatetime(new Date());
						npe.setExtentionid(extno.getId());
						npe.setHostid(extno.getHostid());
						npe.setNumberpoolid(np);
						numberPoolExtentionRelaRepository.save(npe);
					}
				}
			}

		}
		return extno ;
	}

	@RequestMapping(value = "/extention/edit")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentionedit(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid, @Valid boolean ismy) {

		map.addAttribute("extention" , extentionRes.findByIdAndOrgi(id, super.getOrgi(request)));

		map.put("pbxHost", pbxHostRes.findById(hostid)) ;

		map.put("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
//
//		map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
//
		map.addAttribute("numberPoolList",numberPoolRepository.findByHostidAndOrgi(hostid,super.getOrgi(request)));
//
		map.addAttribute("numberPoolExtentionRelaList",numberPoolRepository.findByExtentionidAndOrgi(id,super.getOrgi(request)));

		return request(super.createRequestPageTempletResponse("/admin/mycallcenter/extention/edit"));
	}

	@RequestMapping(value = "/extention/update")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentionupdate(ModelMap map , HttpServletRequest request , @Valid Extention extention,@Valid String[] numberPool, @Valid boolean ismy) {
		if(!StringUtils.isBlank(extention.getId())){
			Extention ext = null;
			//多租户下超级管理员可以编辑其他租户
			if(super.isEnabletneantAndSuperUser(request)){
				ext = extentionRes.findById(extention.getId()) ;
			}else{
				ext = extentionRes.findByIdAndOrgi(extention.getId(), super.getOrgi(request)) ;
			}

			if(ext!=null){
//				ext.setExtention(extention.getExtention());//分机号不能修改
				if(!StringUtils.isBlank(extention.getPassword())){
					ext.setPassword(extention.getPassword());
				}
				ext.setPlaynum(extention.isPlaynum());
				ext.setCallout(extention.isCallout());
				ext.setRecord(extention.isRecord());
				//ext.setExtype(extention.getExtype());
				ext.setSubtype(extention.getSubtype());
				ext.setDescription(extention.getDescription());

				ext.setMediapath(extention.getMediapath());

				//ext.setSiptrunk(extention.getSiptrunk());
				ext.setEnablewebrtc(extention.isEnablewebrtc());

				ext.setAutoanswer(extention.getAutoanswer());

				ext.setUpdatetime(new Date());
				extentionRes.save(ext) ;

				/*List<NumberPoolExtentionRela> NumberPoolExtentionRelaList = numberPoolExtentionRelaRepository.findByHostidAndExtentionid(ext.getHostid(),ext.getId());
				numberPoolExtentionRelaRepository.delete(NumberPoolExtentionRelaList);
				if(numberPool != null && numberPool.length > 0){
					for(String np : numberPool){
						if(StringUtils.isNotBlank(np)){
							NumberPoolExtentionRela npe = new NumberPoolExtentionRela();
							npe.setCreater(super.getUser(request).getId());
							npe.setOrgi(ext.getOrgi());
							npe.setCreatetime(new Date());
							npe.setExtentionid(ext.getId());
							npe.setHostid(ext.getHostid());
							npe.setNumberpoolid(np);
							numberPoolExtentionRelaRepository.save(npe);
						}
					}
				}*/

				List<CallCenterAgent> callOutAgentList = CallOutQuene.extention(ext.getExtention()) ;
				for(CallCenterAgent callOutAgent : callOutAgentList) {
					callOutAgent.setSiptrunk(ext.getSiptrunk());
					CacheHelper.getCallCenterAgentCacheBean().put(callOutAgent.getUserid(), callOutAgent, callOutAgent.getOrgi());
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/mycallcenter/extention.html?hostid="+extention.getHostid()+(ismy?"&ismy=true":"")));
	}

	@RequestMapping(value = "/extention/ivr")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView ivr(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid,@Valid boolean ismy) {
		Extention ext = extentionRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
		map.addAttribute("extention" ,ext);
		if(super.isEnabletneant()){
			map.addAttribute("pbxHost" , pbxHostRes.findById(hostid));
		}else{
			map.addAttribute("pbxHost" , pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request)));
		}
		map.put("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));

		map.put("serviceAiList",serviceAiRes.findByOrgi(super.getOrgi(request)) ) ;
		map.put("queList",queSurveyProcessRes.findByOrgi(super.getOrgi(request)) ) ;
		map.put("salesPatterList",salesPatterRes.findByOrgi(super.getOrgi(request)) ) ;
		if (ismy) {
			map.addAttribute("ismy",true);
		}
		return request(super.createRequestPageTempletResponse("/admin/mycallcenter/extention/ivr"));
	}

	@RequestMapping(value = "/extention/ivr/update")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView ivrupdate(ModelMap map , HttpServletRequest request , @Valid Extention extention,@Valid boolean ismy) {
		if(!StringUtils.isBlank(extention.getId())){
			Extention ext = extentionRes.findByIdAndOrgi(extention.getId(), super.getOrgi(request)) ;
			if(ext!=null){

				ext.setEnableai(extention.getEnableai());
				ext.setAiid(extention.getAiid());
				ext.setSceneid(extention.getSceneid());
				ext.setWelcomemsg(extention.getWelcomemsg()) ;
				ext.setWaitmsg(extention.getWaitmsg())       ;
				ext.setTipmessage(extention.getTipmessage());

				ext.setErrormessage(extention.getErrormessage());

				ext.setAitype(extention.getAitype());
				ext.setBustype(extention.getBustype());
				ext.setProid(extention.getProid());
				ext.setQueid(extention.getQueid());

				ext.setWaittime(extention.getWaittime());
				ext.setWaittiptimes(extention.getWaittiptimes());
				ext.setLanguage(extention.getLanguage());

				ext.setEoseng(extention.getEoseng());
				ext.setSoseng(extention.getSoseng());
				ext.setEostime(extention.getEostime());
				extentionRes.save(ext) ;
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/mycallcenter/extention.html?hostid="+extention.getHostid()+(ismy?"&ismy=true":"")));
	}

	@RequestMapping(value = "/extention/delete")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentiondelete(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid) {
		if(!StringUtils.isBlank(id)){
			Extention extention = extentionRes.findByIdAndOrgi(id, super.getOrgi(request)) ;

			if(extention!=null && !StringUtils.isBlank(extention.getUserid())) {
				User user = null;
				//多租户下超级管理员可以编辑其他租户
				if(super.isEnabletneantAndSuperUser(request)){
					user = userRes.findById(extention.getUserid()) ;
				}else{
					user = userRes.findByIdAndOrgi(extention.getUserid(), super.getOrgi(request)) ;
				}
				if(user!=null) {
					user.setBindext(false);
					user.setExtid(null);
					user.setExtno(null);
					user.setHostid(null);
					userRes.save(user) ;
				}
			}
			extentionRes.delete(id);
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/mycallcenter/extention.html?hostid="+hostid));
	}


	@RequestMapping(value = "/extention/assign")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentionAssign(ModelMap map , HttpServletRequest request , @Valid final String hostid) {
		map.addAttribute("hostid" , hostid);

		//领取机器人分机号
		List<Extention> extentionList = extentionRes.findAll(new Specification<Extention>() {
			@Override
			public Predicate toPredicate(Root<Extention> root,
										 CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				list.add(cb.equal(root.get("hostid").as(String.class), hostid));
				//查出未分配的
				list.add(cb.equal(root.get("assigned").as(Boolean.class),false));
				list.add(cb.equal(root.get("extype").as(String.class),UKDataContext.ExtentionType.IVR.toString()));
				Predicate[] p = new Predicate[list.size()];

				query.where(cb.and(list.toArray(p)));
				//添加排序的功能
				query.orderBy(cb.asc(root.get("extention").as(String.class)));

				return query.getRestriction();

			}
		});
		map.addAttribute("extentionList" , extentionList);


		return request(super.createRequestPageTempletResponse("/admin/mycallcenter/extention/assign"));
	}

	/**
	 * 将分机分配给租户
	 * @param map
	 * @param request
	 * @param ids
	 * @param hostid
	 * @return
	 */
	@RequestMapping(value = "/extention/assigned")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentionassign(ModelMap map , HttpServletRequest request , @Valid String ids , @Valid String hostid) {
		String msg = "";
		String orgi = super.getOrgi(request);
		if(ids != null && StringUtils.isNotBlank(ids)){

			String[] extentions = ids.split("[,\\|，]");;

			if(extentions.length > 0 ){

				for(String nb : extentions){
					List<Extention> list = new ArrayList<>();
					if(StringUtils.isNotBlank(nb)){
						Extention extention = extentionRes.findById(nb) ;
						if(extention!=null && !extention.isAssigned() && UKDataContext.ExtentionType.IVR.toString().equals(extention.getExtype())) {
							extention.setOrgi(orgi);
							extention.setAssigned(true);
							list.add(extention);
						}
					}

					//总数不能超过 机器人并发数
					List<Extention> extentionList = extentionRes.findByExtypeAndHostidAndOrgi(UKDataContext.ExtentionType.IVR.toString(),hostid,orgi);
					Tenant tenant = tenantRepository.findByTenantcode(super.getOrgi(request));
					if(tenant != null){
						if(extentionList.size() < tenant.getRobotagentnum()){
							if((extentionList.size() + list.size()) > tenant.getRobotagentnum()){
								int overnum = (extentionList.size() + list.size()) - tenant.getRobotagentnum();
								while (overnum > 0){
									list.remove(0);
									overnum = (extentionList.size() + list.size()) - tenant.getRobotagentnum();
								}
								extentionRes.save(list);
								msg = "robotagentnum_part_over";
							}else{
								extentionRes.save(list);
							}
						}else{
							msg = "robotagentnum_over";
						}
					}

				}
			}
		}

		return request(super.createRequestPageTempletResponse("redirect:/admin/mycallcenter/extention.html?hostid="+hostid + "&msg="+msg));
	}


	/**
	 * 取消 分配给租户
	 * @param map
	 * @param request
	 * @param id
	 * @param hostid
	 * @return
	 */
	@RequestMapping(value = "/extention/cancelassigned")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentioncancelAssign(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid ) {

		if(id != null && StringUtils.isNotBlank(id)){
			Extention extention = extentionRes.findById(id) ;
			if(extention!=null && extention.isAssigned() && extention.getOrgi().equals(super.getOrgi(request))) {
				extention.setOrgi(UKDataContext.SYSTEM_ORGI);
				extention.setAssigned(false);
				extentionRes.save(extention);
			}
		}

		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+hostid));
	}
}
